class Board < ActiveRecord::Base
  belongs_to :section
  has_and_belongs_to_many :moderators, 
                          :class_name => "User",
                          :join_table => "boards_moderators", 
                          :association_foreign_key => "moderator_id"
  
  has_many                :posts, :dependent => :destroy
  
  validates_presence_of   :title
  validates_presence_of   :section
  
  def discussions
    Post.find(:all, 
              :conditions => ['board_id = ? AND parent_id IS NULL', id],
              :order=>'created_at DESC')
  end
  
  def last_post_time
    last_post.created_at
    # most_recent_update = Post.find(:first, :order=>'updated_at DESC').created_at
  end
  
  def last_post
    most_recent_creation = posts.find(:first, :order=>'created_at DESC')
    most_recent_update   = posts.find(:first, :order=>'updated_at DESC', 
                                      :conditions =>['updated_at IS NOT NULL'])
    if most_recent_update and 
       most_recent_creation.created_at < most_recent_update.updated_at
      most_recent_update
    else
      most_recent_creation
    end
  end
  
  def section_title
    section.title
  end
  
  #def section_title=(new_title)
  #  section.title = new_title
  #  section.save!
  #end
  
end
